package com.bountytask.service.impl;
import com.bountytask.dao.TaskDao;
import com.bountytask.dao.UserDao;
import com.bountytask.dao.UserTaskDao;
import com.bountytask.entity.Task;
import com.bountytask.entity.UserInfo;
import com.bountytask.entity.UserTask;
import com.bountytask.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskDao taskDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserTaskDao userTaskDao;

    /**
     * 修改任务信息
     */
    public int updateTask(Task task){
        if (taskDao.updateTask(task)!=1)
            return 400;
        return 200;
    }

    /**
     * 根据id获取任务
     */
    public Task getTaskById(long id){
        return taskDao.getTaskById(id);
    }

    /**
     * 接任务
     */
    @Transactional
    public int takeTaskService(long userId,long taskId){
        Task task = taskDao.getTaskById(taskId);
        UserInfo user = userDao.getUserById(userId);
        if (task.getTaskNumber()==0)
            return 401;
        if (task.getTaskStatus()==1)
            return 400;
        HashMap<String, Object> map = new HashMap<>();
        //更新user表
        map.put("userid",userId);
        map.put("getNum",user.getGetNum()+1);
        userDao.updateUserForTake(map);
        map.clear();
        //更新task表
        map.put("taskid",taskId);
        map.put("taskNumber",task.getTaskNumber()-1);
        map.put("getNum",task.getGetNum()+1);
        taskDao.updateTaskForTake(map);
        //user_task表添加
        UserTask userTask = new UserTask();
        userTask.setTaskId(taskId);
        userTask.setUserId(userId);
        userTask.setRole(0);
        userTask.setStatus(1);
        if (userTaskDao.addUserTask(userTask)!=1)
            return 400;
        return 200;
    }

    /**
     * 发布任务
     */
    @Transactional
    public long postTask(Task newTask,long userId){
        float userMoney=userDao.getUserById(userId).getMoney();
        if ( userMoney < newTask.getTotal())
            return 0;
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",userId);
        map.put("money",userMoney-newTask.getTotal());
        map.put("postNum",userDao.getUserById(userId).getPostNum()+1);
        userDao.updateUserForPost(map);
        newTask.setStartTime(new Date());
        //task表添加任务
        if (taskDao.addTask(newTask)!=1)
            return -1;
        //清空map
        UserTask userTask = new UserTask();
        userTask.setTaskId(newTask.getId());
        userTask.setUserId(userId);
        userTask.setRole(1);
        userTask.setStatus(1);
        if (userTaskDao.addUserTask(userTask)!=1)
            return -1;
        return newTask.getId();
    }

    /**
     *根据条件查找任务
     */
    public List<Task> getTasksByCondition(String keyword,String category,String campus){
        HashMap<String, Object> map = new HashMap<>();
        String nowDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        map.put("keyword",keyword);
        map.put("category",category);
        map.put("campus",campus);
        map.put("nowDate",nowDate);
        return taskDao.getTasksByCondition(map);
    }

    /**
     * 根据条件排序
     */
    public List<Task> sortTasks(List<Task> nosortTasks,String condition){
        switch (condition) {
            case "紧急":
                return sortTaskByDeadline(nosortTasks);
            case "最新":
                return sortTaskByStartTime(nosortTasks);
            case "赏金最高":
                return sortTaskByBounty(nosortTasks);
        }
        return nosortTasks;
    }

    /**
     * 根据悬赏金额排序
     */
    public List<Task> sortTaskByBounty(List<Task> nosortTasks){
        nosortTasks.sort((o1, o2) -> {
            if (o1.getBounty()>o2.getBounty())
                return -1;
            else if (o1.getBounty()<o2.getBounty())
                return 1;
            else return 0;
        });
        return nosortTasks;
    }

    /**
     * 根据距离截止时间排序
     */
    public List<Task> sortTaskByDeadline(List<Task> nosortTasks){
        nosortTasks.sort((o1, o2) -> {
            if (o1.getDeadline().after(o2.getDeadline()))
                return 1;
            else if (o1.getDeadline().before(o2.getDeadline()))
                return -1;
            else return 0;
        });
        return nosortTasks;
    }

    /**
     * 根据发布时间最晚排序
     */
    public List<Task> sortTaskByStartTime(List<Task> nosortTasks){
        nosortTasks.sort((o1, o2) -> {
            if (o1.getStartTime().after(o2.getStartTime()))
                return -1;
            else if (o1.getStartTime().before(o2.getStartTime()))
                return 1;
            else return 0;
        });
        return nosortTasks;
    }

    /**
     * 认定无效
     * @param taskid
     * @param userid
     * @return
     */
    @Transactional
    public int rejectTask(long taskid,long userid){
        HashMap<String,Object> map=new HashMap<>();
        map.put("taskid",taskid);
        map.put("userid",userid);
        Task task=taskDao.getTaskById(taskid);
        task.setFinishNum(task.getFinishNum()-1);
        if(taskDao.rejectTask(map)!=1||taskDao.deleteStatus(taskid)!=1||taskDao.updateTask(task)!=1)
        {
            return 400;
        }
        return 200;
    }

    /**
     * 获取所有在线的，被人领取过的任务
     */
    public List<Long> getAllOnlineTask(){
        return taskDao.getAllTask(new Date());
    }
}
